﻿using System;
using System.Collections.Generic;
using System.Linq;
using ChuanYe.Models;
using ChuanYe.IBLL;
using Microsoft.Practices.Unity;
using ChuanYe.Commom;
using ChuanYe.Models.Model;
using System.Web.Http.Cors;

namespace SJPlatForm.Web.Controllers
{
    /// <summary>
    /// 平安报送模块
    /// </summary>
    [EnableCors("*", "*", "*")]
    public class SafetyInfoController : BaseApiController
    {
        [Dependency]
        public ISafetyInfoBLL s_bll { get; set; }

        [Dependency]
        public ISms_SendInfoBLL m_bll { get; set; }

        [Dependency]
        public IUsersInfosBLL  u_bll { get; set; }

        //public ActionResult SendSafetyInfo()
        //{
        //    //DateTime endDate = Convert.ToDateTime(DateTime.Now.ToShortDateString()+ " 23:59:59");
        //    //DateTime stateDate = DateTime.Now.AddDays(-7);
        //    //GetSafetyInfoListByDay();
        //    return View();
        //}

        /// <summary>
        /// 获取电话簿列表
        /// </summary>
        /// <returns>电话簿列表</returns>
        [System.Web.Http.HttpPost]
        public List<View_SmsPhone> GetLeader()
        {
            try
            {
                return s_bll.GetLeader();
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                List<View_SmsPhone> result = new List<View_SmsPhone>();
                return result;
            }
        }

        /// <summary>
        /// 获取电话簿列表 2018/07/11 外部用户
        /// </summary>
        /// <returns>电话簿列表</returns>
        [System.Web.Http.HttpPost]
        public dynamic GetLeader2(dynamic obj)
        {
            try
            {
                List<View_SmsPhone> result = new List<View_SmsPhone>();
                int selectType = obj == null || Convert.ToInt32(obj.SelectType) == 0 ? 1 : Convert.ToInt32(obj.SelectType);
                List<U_OutsideUserInfos> outList= u_bll.OutsideUserInfosSelect(selectType);
                result = s_bll.GetLeader();
                for (int i = 0; i < outList.Count; i++)
                {
                    result.Add(new View_SmsPhone() {
                          Phone=outList[i].UserPhone,
                          UserName=outList[i].UserName,
                          UserID=1000000+outList[i].ID
                    });
                }
                return result;

            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                return new List<View_SmsPhone>();
            }
        }


        /// <summary>
        /// 市局保存报送信息
        /// </summary>
        /// <param name="obj">报送信息：ReportInfo，接收人信息：ReceiversInfo,接收人信息格式：人员姓名，手机号|人员姓名，手机号</param>
        /// <returns>true:保存成功，false:保存失败</returns>
        [System.Web.Http.HttpPost]
        public bool CreateSafetyInfo(dynamic obj)
        {
            try
            {
                Sms_SendInfo SmsModel = new Sms_SendInfo();
                string Receivers = "";
                SmsModel.SmsInfo = obj.ReportInfo;
                SmsModel.SendDate = DateTime.Now;
                SmsModel.Sender = GetLoginInfo(obj.key.ToString()).UserName;
                SmsModel.SenderCode = GetLoginInfo(obj.key.ToString()).UserCode;
                //SmsModel.AchievedDate = DateTime.Now;//上线前删除
                SmsModel.IsAchieved = false;
                SmsModel.IsSafety = true;
                SmsModel.SafetyCode = Guid.NewGuid().ToString();
                string ReceiversInfo = obj.ReceiversInfo;
                string[] ReceiverList = ReceiversInfo.Split('|');
                bool IsSend = false;
                foreach (var item in ReceiverList)
                {
                    string[] info = item.Split(',');
                    SmsModel.MobileCode = info[1];
                    SmsModel.Receiver = info[0];
                    Receivers += info[0] + ",";
                    IsSend = m_bll.CreateSms_SendInfo(SmsModel);
                }
                bool RT = IsSend;
                if (RT)
                {
                    Log.Info(obj.key.ToString(), "平安报送", "平安报送成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 获取报送短信信息
        /// </summary>
        /// <param name="obj">开始时间：stateTime，结束时间：endTime，短信内容：SmsInfo，页数：page，行数：rows</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public SafetySms_SendInfoResult GetLastSafetyInfo(dynamic obj)
        {
            try
            {
                SafetySms_SendInfoSearch search = new SafetySms_SendInfoSearch();

                if (obj.stateTime != null && obj.stateTime != "")
                {
                    search.stateTime = ValueConvert.StateTimeConvert(obj.stateTime);
                }
                else
                {
                    search.stateTime = SJPlatForm.Web.Common.ConfigHelper.StateTime;
                }
                if (obj.endTime != null && obj.endTime != "")
                {
                    search.endTime = ValueConvert.EndTimeConvert(obj.endTime);
                }
                else
                {
                    search.endTime = DateTime.Now;
                }
                search.SmsInfo = obj.SmsInfo == null ? "" : obj.SmsInfo;
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return s_bll.GetLastSafetyInfo(search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                SafetySms_SendInfoResult result = new SafetySms_SendInfoResult();
                return result;
            }
        }

        /// <summary>
        /// 获取某天各地区平安报送情况
        /// </summary>
        /// <param name="obj">时间：ReportDate，页数：page，行数：rows</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public SafetyInfoResult GetSafetyInfoListByDay(dynamic obj)
        {
            try
            {
                SafetyInfo model = new SafetyInfo();
                //model.ReportDate = DateTime.Parse("2007-05-09");
                model.ReportDate = Convert.ToDateTime(obj.ReportDate);
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);

                return s_bll.GetSafetyInfoListByDay(model, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                SafetyInfoResult result = new SafetyInfoResult();
                return result;
            }
        }

        /// <summary>
        /// 市局获取报送统计列表
        /// </summary>
        /// <param name="obj">开始时间：stateTime，结束时间：endTime</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public List<SP_SafetyInfoStatistics_Result> GetSafetyInfoStatistics(dynamic obj)
        {
            try
            {
                SafetyInfoStatisticsSearch search = new SafetyInfoStatisticsSearch();
                search.stateTime = ValueConvert.StateTimeConvert(Convert.ToDateTime(obj.stateTime));
                DateTime endTime = ValueConvert.StateTimeConvert(obj.endTime);

                //if(endTime.ToShortDateString() == DateTime.Now.ToShortDateString() && search.stateTime !=endTime)
                //{
                //    if (DateTime.Now.Hour < 15)
                //    {
                //        endTime = DateTime.Now.AddDays(-1);
                //    }
                //}
                search.endTime = ValueConvert.EndTimeConvert(endTime);


                return s_bll.GetSafetyInfoStatistics(search);
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                List<SP_SafetyInfoStatistics_Result> result = new List<SP_SafetyInfoStatistics_Result>();
                return result;
            }
        }

        /// <summary>
        /// 区县保存报送信息
        /// </summary>
        /// <param name="obj">报送人：ReportPerson，报送内容：ReportInfo</param>
        /// <returns>1:成功，0:失败,2:重复报送，3:不在下午3点到5点半之间，-1：出错</returns>
        [System.Web.Http.HttpPost]
        public int CreateDistrictSafetyInfo(dynamic obj)
        {
            try
            {
                int hour = DateTime.Now.Hour;
                int Minute = DateTime.Now.Minute;
                if (hour <15|| hour>17||(hour==17&& Minute>30))
                {
                   // return 3;
                }
                int DepId = GetLoginInfo(obj.key.ToString()).DepID;
                int IsSend = s_bll.IsSendToday(DepId);
                if (IsSend == 1) {
                    return 2;
                }
                SafetyInfo model = new SafetyInfo();
                model.ReportPerson = obj.ReportPerson;
                model.IsSafety = false;
                model.ReportInfo = obj.ReportInfo;
                model.ReportDate = DateTime.Now.Date;
                model.ReportPersonCode = GetLoginInfo(obj.key.ToString()).UserCode;
                model.ReportDepartment = GetLoginInfo(obj.key.ToString()).DepName;
                model.DepId = GetLoginInfo(obj.key.ToString()).DepID;
                model.CreateDate = DateTime.Now;
                model.IsOwnReport = true;
                int RT= s_bll.CreateSafetyInfo(model) == true ? 1 : 0;
                if (RT>0)
                {
                    Log.Info(obj.key.ToString(), "平安报送", "区县平安报送成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 区县获取报送统计列表
        /// </summary>
        /// <param name="obj">开始时间：stateTime，结束时间：endTime</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public SP_DistrictSafetyInfoStatistics_Result GetDistrictSafetyInfoStatistics(dynamic obj)
        {
            try
            {
                DistrictSafetyInfoStatisticsSearch search = new DistrictSafetyInfoStatisticsSearch();
                search.stateTime = obj.stateTime;
                search.stateTime = search.stateTime.StateTimeConvert();
                search.endTime = obj.endTime;
                search.endTime = search.endTime.EndTimeConvert();
                search.DepId = GetLoginInfo(obj.key.ToString()).DepID;
                var result= s_bll.GetDistrictSafetyInfoStatistics(search);

                //计算间隔天数
                TimeSpan ts = search.endTime - search.stateTime;
                double dDays = ts.TotalDays;
                int iDays = ts.Days;
                if (dDays - iDays > 0)
                {
                    iDays = iDays + 1;
                }
                if (result.safeIsCount == 0 && result.safeNotCount <= 0 && result.allCount <= 0 && result.safepercent == 0)
                {

                    result.safeIsCount = 0;
                    result.safeNotCount = iDays;
                    result.allCount = iDays;
                    result.safepercent = 0;
                }

               

                return result;
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                SP_DistrictSafetyInfoStatistics_Result result = new SP_DistrictSafetyInfoStatistics_Result();
                return result;
            }
        }

        /// <summary>
        /// 获取本单位名称
        /// </summary>
        /// <param name="obj">key:用户ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public string GetDepName(dynamic obj)
        {
            try
            {
                return GetLoginInfo(obj.key.ToString()).DepName;
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                return "";
            }
        }

        /// <summary>
        /// 区县逐月查询报送记录
        /// </summary>
        /// <param name="obj">年月时间:Time</param>
        /// <returns>平安报送列表</returns>
        [System.Web.Http.HttpPost]
        public List<SafetyInfo> GetSafetyInfoForMonth(dynamic obj)
        {
            try
            {
                SafetyInfoForMonthSearch search = new SafetyInfoForMonthSearch();
                search.stateTime = ValueConvert.MonthFristDay(obj.Time);
                search.endTime = ValueConvert.MonthLastDay(obj.Time);
                search.DepId = GetLoginInfo(obj.key.ToString()).DepID;
                List<SafetyInfo> SafetyInfoList= s_bll.GetSafetyInfoForMonth(search);
                List<SafetyInfo> result = new List<SafetyInfo>();
                int end = search.endTime.Day;
                for (int i = end; i > 0; i--)
                {
                    DateTime Date = search.endTime.AddDays(0 - end + i).Date;
                    SafetyInfo Safety = SafetyInfoList.FirstOrDefault(m => m.ReportDate == Date);
                    if (Safety == null)
                    {
                        SafetyInfo SafetyNew = new SafetyInfo();
                        SafetyNew.ReportDate = Date;
                        result.Add(SafetyNew);
                    }
                    else {
                        result.Add(Safety);
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                List<SafetyInfo> result = new List<SafetyInfo>();
                return result;
            }
        }

        /// <summary>
        /// 添加，修改平安报送备注
        /// </summary>
        /// <param name="obj">平安报送ID：ID，备注：Remarks，平安报送部门ID：DepID，部门名称：DepName，报送时间：Date</param>
        /// <returns>1：修改成功，0：修改失败，-1：出错</returns>
        [System.Web.Http.HttpPost]
        public int SafetyInfoUpdate(dynamic obj)
        {
            try
            {
                int RT = 0;
                if (obj.ID != null&&obj.ID.ToString() != "")
                {
                    SafetyInfo model = new SafetyInfo();
                    model.ID = obj.ID;
                    model.Remarks = obj.Remarks;
                    RT = s_bll.SafetyInfoUpdate(model);
                    if (RT > 0)
                    {
                        Log.Info(obj.key.ToString(), "平安报送", "修改平安报送备注成功！");
                    }
                }
                else
                {
                    DateTime reportDate= Convert.ToDateTime(obj.Date);
                    int DepId = Convert.ToInt32(obj.DepID);
                    int IsSend = s_bll.IsSendToday(DepId, reportDate);
                    if (IsSend == 1)
                    {
                        return 2;
                    }
                    SafetyInfo model = new SafetyInfo();
                    model.ReportPerson = GetLoginInfo(obj.key.ToString()).UserName;
                    model.IsSafety = false;
                    model.ReportDate = reportDate;
                    model.ReportPersonCode = GetLoginInfo(obj.key.ToString()).UserCode;
                    model.ReportDepartment = obj.DepName;
                    model.DepId = Convert.ToInt32(obj.DepID); 
                    model.CreateDate =null;
                    model.ReportInfo = null;
                    model.IsOwnReport = false;
                    model.Remarks= obj.Remarks;
                    RT = s_bll.CreateSafetyInfo(model) == true ? 1 : 0;
                    if (RT > 0)
                    {
                        Log.Info(obj.key.ToString(), "平安报送", "添加平安报送备注成功！");
                    }
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 获取本区县今日是否已报送平安
        /// </summary>
        /// <param name="obj">key:用户ID</param>
        /// <returns>0：没有发送，1：已发送，-1：出错</returns>
        [System.Web.Http.HttpPost]
        public int IsSendToday(dynamic obj)
        {
            try
            {
                int DepId = GetLoginInfo(obj.key.ToString()).DepID;
                return s_bll.IsSendToday(DepId);
            }
            catch (Exception ex)
            {
                Log.Error("SafetyInfoController", ex.ToString());
                return -1;
            }
        }

        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }
    }
}